package com.linxs.me.intefaces.controller;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.net.URL;

import org.htmlcleaner.HtmlCleaner;
import org.htmlcleaner.TagNode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.kissme.core.orm.Page;
import com.linxs.me.application.blog.BlogService;
import com.linxs.me.domain.blog.Blog;

/**
 * 
 * @author Linxiaosheng
 *
 */
@Controller
@RequestMapping(value = "/admin")
public class BlogController {
	 
	@Autowired
	private BlogService blogService; 
	
	@RequestMapping(value = "/blog", method = RequestMethod.GET) 
	public String list(Model model) {
		model.addAttribute("page", blogService.queryPage(new Page<Blog>().setPageNo(1).setPageSize(10)));
		return "admin/blog/list";
	}
	
	@RequestMapping(value = "/blog/create", method = RequestMethod.GET)
	public String create(Model model) {
		model.addAttribute("blog", new Blog());
		return "admin/blog/form";
	}
	
	@RequestMapping(value = "/blog/create", method = RequestMethod.POST) 
	public String create(Blog blog) {
		blogService.save(blog);
		return "redirect:admin/blog/list";
	}
	
	@RequestMapping(value = "/crawl", method = RequestMethod.GET)
	public String crawl() throws Exception {
		BufferedReader br = new BufferedReader(new FileReader("C:\\Users\\Administrator\\Desktop\\123.txt"));
		String data = br.readLine();// 一次读入一行，直到读入null为文件结束
		while (data != null) {
			// System.out.println(data);
			ohYes(data); 
			data = br.readLine(); // 接着读下一行
		}
		return "redirect:admin/blog/list";
	}
	
//	public static void main(String[] args) throws Exception {
//		BufferedReader br = new BufferedReader(new FileReader("C:\\Users\\Administrator\\Desktop\\123.txt"));
//		String data = br.readLine();// 一次读入一行，直到读入null为文件结束
//		while (data != null) {
//			ohYes(data);
//			data = br.readLine(); // 接着读下一行
//		}
//	}

	private void ohYes(String data) throws Exception {
		URL url = new URL(data);
		HtmlCleaner cleaner = new HtmlCleaner();
		TagNode node = cleaner.clean(url, "utf-8");
		Object[] titles = node.evaluateXPath("//h1[@class='title']");
		Object[] contents = node.evaluateXPath("//div[@class='rich-content']");
		Blog blog = new Blog();
		
		for (Object title : titles) {
			blog.setTitle(((TagNode) title).getText().toString());
//			System.out.println(((TagNode) title).getText());
			// tagNode).getAttributeByName("href"));
		}
		for (Object tagNode : contents) {
			blog.setContent(((TagNode) tagNode).getText().toString());
			System.out.println(((TagNode) tagNode).getText());
			// tagNode).getAttributeByName("href"));
		}
//		blogService.save(blog);
	}
}
